{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "601743c8",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[['E:\\\\oo\\\\oo\\\\csv\\\\1-1.csv', '1.1'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\2-1.csv', '2.1'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\2-2.csv', '2.2'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\2-3.csv', '2.3'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\3-1.csv', '3.1'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\3-2.csv', '3.2'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\3-3.csv', '3.3'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-1.csv', '4.1'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-2.csv', '4.2'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-3.csv', '4.3'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-4.csv', '4.4'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-5.csv', '4.5'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-6.csv', '4.6'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\4-7.csv', '4.7'],\n",
       " ['E:\\\\oo\\\\oo\\\\csv\\\\5-1.csv', '5.1']]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class ExecuteCsv_rewrite:\n",
    "    def __init__(self,csv_files,title,word,save_path):\n",
    "        \n",
    "        self.save_path = save_path\n",
    "\n",
    "        df = pd.read_csv(csv_files[0],engine = \"python\")\n",
    "        for i in csv_files[1:]:\n",
    "            f2=open(i)#############自己修改###########\n",
    "            df2 = pd.read_csv(f2)#############自己修改###########\n",
    "            df = pd.concat([df,df2])\n",
    "        count = 0\n",
    "        df= df.reset_index(drop=True)\n",
    "        index_dict ={}\n",
    "        \n",
    "        dataMat = []\n",
    "        self.max_limit = min(30,int(df[\"tb\"].max())+5)\n",
    "        K = len(df['GRID_CODE'].value_counts())\n",
    "        for i in range(len(df)):\n",
    "            if df.GRID_CODE[i] not in index_dict:\n",
    "                index_dict[df.GRID_CODE[i]] = count\n",
    "                count += 1\n",
    "\n",
    "            x = int((float(df.tb[i])/0.5 + 1))\n",
    "            if df.E_sum[i] >0 :\n",
    "                y = int((float(df.E_sum[i])/(5.893*2.4987*0.5) + 1))\n",
    "            else:\n",
    "                y = int((float(df.E_sum[i])/(5.893*2.4987*0.5) ))\n",
    "            x_ret = x*0.5\n",
    "            y_ret = y*(5.893*2.4987*0.5)\n",
    "                \n",
    "            retlist = [x_ret,y_ret] + [0] * K\n",
    "            retlist[index_dict[df.GRID_CODE[i]]+2] = 1\n",
    "            dataMat.append(retlist)\n",
    "                \n",
    "        df = pd.DataFrame(dataMat)\n",
    "        self.columns =  [\"tb\",\"e_sum\"] + list(index_dict.keys())\n",
    "        df.columns  = self.columns\n",
    "        self.word = word\n",
    "        groupedMat = df.groupby([df[\"tb\"],df[\"e_sum\"]]).sum()\n",
    "        groupedMat.to_csv(self.save_path + \"\\\\\" + (title.replace(\"/\",\"_\")) + word[:-1] + \"_格子图占比.csv\") \n",
    "        self.lat_csv = self.save_path + \"\\\\\" + (title.replace(\"/\",\"_\")) + self.word[:-1] + \"_格子图占比.csv\"\n",
    "        \n",
    "    def set_save_path(self,save_path):\n",
    "        try : \n",
    "            os.mkdir(save_path)\n",
    "        except:\n",
    "            pass\n",
    "        self.save_path = save_path\n",
    "        \n",
    "    def start_execute(self,title,csv1,max_limit,k,tb,E,sign):\n",
    "\n",
    "        f5=open(csv1)#############自己修改###########\n",
    "        df = pd.read_csv(f5)#############自己修改###########\n",
    "        \n",
    "        tb_count_list = [[0,0,0,0,0,0,0] for i in range(12)]\n",
    "        for i in range(len(df)):\n",
    "            if df.E_sum[i] >  4*5.893*2.4987* df.tb[i]: a = 0 #0.25\n",
    "\n",
    "            elif df.E_sum[i] >  2*5.893*2.4987* df.tb[i]: a = 1 #0.5\n",
    "\n",
    "            elif df.E_sum[i] >  5.893*2.4987* df.tb[i]: a = 2\n",
    "            elif df.E_sum[i] >  (1/3)*5.893*2.4987* df.tb[i] :a = 3\n",
    "            elif df.E_sum[i] >= 0: a = 4\n",
    "            elif df.E_sum[i] >  -(1/3)*5.893*2.4987* df.tb[i] :a = 5\n",
    "            elif df.E_sum[i] >  -0.5*5.893*2.4987* df.tb[i]: a = 6 #4\n",
    "            elif df.E_sum[i] >  -(3/5)*5.893*2.4987* df.tb[i] :a = 7 # 5\n",
    "            elif df.E_sum[i] >  -(2/3)*5.893*2.4987* df.tb[i] :a = 8 # 6\n",
    "            elif df.E_sum[i] >  -5.893*2.4987* df.tb[i]: a = 9 # p = 0\n",
    "            else : a = 10\n",
    "\n",
    "            if df.tb[i] <2: b = 0\n",
    "            elif df.tb[i]<6: b = 1\n",
    "            elif df.tb[i]<10: b = 2\n",
    "            elif df.tb[i]<14: b = 3\n",
    "            elif df.tb[i]<22: b = 4\n",
    "            elif df.tb[i]<30: b = 5\n",
    "\n",
    "            tb_count_list[a][b] += 1\n",
    "        self.tb_ratio = [[i/len(df.tb) for i in tb_count_list[j]] for j in range(12)]    \n",
    "\n",
    "        latticeImage = LatticeImage(self.lat_csv,title,self.tb_ratio,tb,E)\n",
    "        save_path = self.save_path + \"\\\\\" +\"群丛\" + csv1.split(\"\\\\\")[-1][:-4] +  \".svg\"\n",
    "        color = getcolor_dict[csv1.split(\"\\\\\")[-1][:-4]]\n",
    "        latticeImage.generate_image(save_path,self.columns,k,df,self.max_limit,color,sign)\n",
    "\n",
    "    def got_true_title(self,i = (\"\",\"\")):\n",
    "        return self.title \n",
    "        \n",
    "from scipy import optimize\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "import math\n",
    "import scipy.stats\n",
    "def linefit(x,y):\n",
    "    N = float(len(x))\n",
    "    sx,sy,sxx,syy,sxy=0,0,0,0,0\n",
    "    for i in range(0,int(N)):\n",
    "        sx  += x[i]\n",
    "        sy  += y[i]\n",
    "        sxx += x[i]*x[i]\n",
    "        syy += y[i]*y[i]\n",
    "        sxy += x[i]*y[i]\n",
    "    a = (sy*sx/N -sxy)/( sx*sx/N -sxx)\n",
    "    b = (sy - a*sx)/N\n",
    "    r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))\n",
    "    p = hypo_test(x,y,a,b)\n",
    "    return a,b,r,p\n",
    "\n",
    "def hypo_test(x,y,a,b):\n",
    "    \"\"\"\n",
    "    2.9更新:假设检验：\n",
    "    对最小二乘拟合得出的拟合线y=ax+b中的a的显著性进行检验\n",
    "\n",
    "    构造t统计量 = a/(sigma^2/n*D(x))^(1/2)\n",
    "    n:样本容量\n",
    "    sigma:对总体方差的估计，sigma^2 = SSE/(n-2) \n",
    "    SSE = (sum(yi^2) - asum(xiyi) - bsum(yi))^0.5\n",
    "    D(x):x的方差\n",
    "    根据t统计量的值及自由度n-2，推出p值\n",
    "    \n",
    "    \n",
    "    \"\"\"\n",
    "    \n",
    "    if len(x) < 2:\n",
    "        return 1\n",
    "    n = len(y)\n",
    "    ybar = sum(y)/n\n",
    "    xbar = sum(x)/n\n",
    "    sse = (sum([yi**2 for yi in y]) - a*sum([x[i]*y[i] for i in range(n)]) - b*sum(y)) ** 0.5\n",
    "    dx = sum([(xi-xbar)**2 for xi in x])\n",
    "    sigma2 = sse/(n-2)\n",
    "    \n",
    "    if sse == 0:\n",
    "        t = 99999999\n",
    "    else:  \n",
    "        t = a/(sigma2/dx)**(1/2)\n",
    "    \n",
    "    return scipy.stats.t.sf(abs(t),n-2) \n",
    "\n",
    "\n",
    "def auto_curve(df,rg,keyword): \n",
    "    x = np.array(df.tb)\n",
    "    y = np.array(df.E_sum)\n",
    "    \n",
    "    line1 = [linefit(x,y)] \n",
    "    if keyword == \"斜\":\n",
    "        k,b,r,p = line1[0]\n",
    "        return {'k_list': \n",
    "                  [{'k':k, 'b': b, 'r': r, 'p':p,'type': 'normal'}],\n",
    "                  'writel': {0: (0, 30), 1: (0, 30), 2: (0, 30)}}\n",
    "    elif keyword == \"斜斜\":\n",
    "        line2,cr1 = get_2_line(x,y)\n",
    "        k1,b1,r1,p1 = line2[0]\n",
    "        k2,b2,r2,p2 = line2[1]\n",
    "        return {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},],\n",
    "                  'writel': {0: (0, cr1[0]), 1: (cr1[0], 30), 2: (0, 30)}}\n",
    "    \n",
    "    \n",
    "    if not rg and keyword:\n",
    "        if keyword == \"水\":\n",
    "            return {'k_list': \n",
    "                      [{'k':0, 'b': np.mean(y), 'r': 0, 'p':None,'type': 'horizon'}],\n",
    "                      'writel': {0: (0, 30), 1: (0, 30), 2: (0, 30)}}\n",
    "        if keyword == \"垂\":\n",
    "            return {'k_list': \n",
    "                      [{'k':np.mean(x), 'b': 0, 'r': 0, 'p':None,'type': 'vertical'}],\n",
    "                      'writel': {0: (0, 30), 1: (0, 30), 2: (0, 30)}}        \n",
    "    elif len(rg) == 1:\n",
    "        p1,p2 = [(x[i],y[i]) for i in range(len(df)) if x[i] < rg[0]],[(x[i],y[i]) for i in range(len(df)) if x[i] >= rg[0]]\n",
    "        x1,y1 = [i[0] for i in p1],[i[1] for i in p1]\n",
    "        x2,y2 = [i[0] for i in p2],[i[1] for i in p2]\n",
    "        if keyword == \"水斜\":\n",
    "            line2 = [[0,np.mean(y1),*linefit(x1,y1)[2:]],linefit(x2,y2)]\n",
    "            k1,b1,r1 = line2[0]\n",
    "            k2,b2,r2,p2 = line2[1]\n",
    "            split = (b1-b2)/(k2-k1) \n",
    "            return  {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':None,'type': 'horizon'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},],\n",
    "                  'writel': {0: (0, split), 1: (split, 30), 2: (0, 30)}}\n",
    "        if keyword == \"斜水\":\n",
    "            line2 = [linefit(x1,y1),[0,np.mean(y2),linefit(x2,y2)[2]]]\n",
    "            k1,b1,r1,p1 = line2[0]\n",
    "            k2,b2,r2 = line2[1]\n",
    "            split = (b1-b2)/(k2-k1) \n",
    "            return  {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':None,'type': 'horizon'},],\n",
    "                  'writel': {0: (0, split), 1: (split, 30), 2: (0, 30)}}\n",
    "        if keyword == \"上垂斜\":\n",
    "            line2 = [None,linefit(x2,y2)]\n",
    "            k2,b2,r2,p2 = line2[1]\n",
    "            line2[0] = [rg[0],k2*rg[0]+b2,0]\n",
    "            split = rg[0]\n",
    "            k1,b1,r1 = line2[0]\n",
    "            return  {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':None,'type': 'up_vertical'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},],\n",
    "                  'writel': {0: (0, split), 1: (split, 30), 2: (0, 30)}}\n",
    "        if keyword == \"下垂斜\":\n",
    "            line2 = [None,linefit(x2,y2)]\n",
    "            k2,b2,r2,p2 = line2[1]\n",
    "            line2[0] = [rg[0],k2*rg[0]+b2,0]\n",
    "            split = rg[0]\n",
    "            k1,b1,r1 = line2[0]\n",
    "            return  {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':None,'type': 'down_vertical'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},],\n",
    "                  'writel': {0: (0, split), 1: (split, 30), 2: (0, 30)}}\n",
    "        if keyword == \"斜上垂\":\n",
    "            line2 = [linefit(x1,y1),None]\n",
    "            k2,b2,r2 = line2[0]\n",
    "            line2[1] = [rg[0],k2*rg[0]+b2,0]\n",
    "            split = rg[0]\n",
    "            k1,b1,r1,p1 = line2[0]\n",
    "            k2,b2,r2 = line2[1]\n",
    "            return  {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':None,'type': 'up_vertical'},],\n",
    "                  'writel': {0: (0, split), 1: (split, 30), 2: (0, 30)}}\n",
    "        if keyword == \"斜下垂\":\n",
    "            line2 = [linefit(x1,y1),None]\n",
    "            k2,b2,r2 = line2[0]\n",
    "            line2[1] = [rg[0],k2*rg[0]+b2,0]\n",
    "            split = rg[0]\n",
    "            k1,b1,r1,p1 = line2[0]\n",
    "            k2,b2,r2 = line2[1]\n",
    "            return  {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':None,'type': 'down_vertical'},],\n",
    "                  'writel': {0: (0, split), 1: (split, 30), 2: (0, 30)}}\n",
    "    elif len(rg) == 2:\n",
    "        p1,p2,p3 =( [(x[i],y[i]) for i in range(len(df)) if x[i] < rg[0]],\n",
    "                    [(x[i],y[i]) for i in range(len(df)) if (rg[1] > x[i] >= rg[0])],\n",
    "                    [(x[i],y[i]) for i in range(len(df)) if x[i] >= rg[1]])\n",
    "            \n",
    "        x1,y1 = [i[0] for i in p1],[i[1] for i in p1]\n",
    "        x2,y2 = [i[0] for i in p2],[i[1] for i in p2]\n",
    "        x3,y3 = [i[0] for i in p3],[i[1] for i in p3]\n",
    "        if keyword == \"水斜斜\":\n",
    "            line3 = [[0,np.mean(y1),linefit(x1,y1)[2]],linefit(x2,y2),linefit(x3,y3)]\n",
    "            k1,b1,r1 = line3[0]\n",
    "            k2,b2,r2,p2 = line3[1]    \n",
    "            k3,b3,r3,p3 = line3[2]  \n",
    "            crossx1 = (b1-b2)/(k2-k1)\n",
    "            crossx2 = (b3-b2)/(k2-k3)\n",
    "            split = (b1-b2)/(k2-k1) \n",
    "            return {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':None,'type': 'horizon'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},\n",
    "                   {'k':k3, 'b': b3, 'r': r3, 'p':p3,'type': 'normal'},],\n",
    "                  'writel': {0: (0, crossx1), 1: (crossx1, crossx2), 2: (crossx2, 30)}}\n",
    "        if keyword == \"斜水斜\":\n",
    "            line3 =  [linefit(x1,y1),[0,np.mean(y2),linefit(x2,y2)[2]],linefit(x3,y3)]\n",
    "            k1,b1,r1,p1 = line3[0]\n",
    "            k2,b2,r2 = line3[1]    \n",
    "            k3,b3,r3,p3 = line3[2]  \n",
    "            crossx1 = (b1-b2)/(k2-k1)\n",
    "            crossx2 = (b3-b2)/(k2-k3)\n",
    "            split = (b1-b2)/(k2-k1) \n",
    "            return {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':None,'type': 'horizon'},\n",
    "                   {'k':k3, 'b': b3, 'r': r3, 'p':p3,'type': 'normal'},],\n",
    "                  'writel': {0: (0, crossx1), 1: (crossx1, crossx2), 2: (crossx2, 30)}}\n",
    "        if keyword == \"斜斜水\":\n",
    "            line3 = [linefit(x1,y1),linefit(x2,y2),[0,np.mean(y3),linefit(x3,y3)[2]]]\n",
    "            k1,b1,r1,p1 = line3[0]\n",
    "            k2,b2,r2,p2 = line3[1]    \n",
    "            k3,b3,r3 = line3[2]  \n",
    "            crossx1 = (b1-b2)/(k2-k1)\n",
    "            crossx2 = (b3-b2)/(k2-k3)\n",
    "            split = (b1-b2)/(k2-k1) \n",
    "            return {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},\n",
    "                   {'k':k3, 'b': b3, 'r': r3, 'p':None,'type': 'horizon'},],\n",
    "                  'writel': {0: (0, crossx1), 1: (crossx1, crossx2), 2: (crossx2, 30)}}\n",
    "\n",
    "    line1 = [linefit(x,y)]\n",
    "    \n",
    "    if len(df.tb) < 15:\n",
    "        k,b,r,p = line1[0]\n",
    "        return {'k_list': \n",
    "                  [{'k':k, 'b': b, 'r': r, 'p':p,'type': 'normal'}],\n",
    "                  'writel': {0: (0, 30), 1: (0, 30), 2: (0, 30)}}\n",
    "    line2,cr1 = get_2_line(x,y)\n",
    "    line3,cr2,cr3 = get_3_line(x,y)\n",
    "    r1,r2,r3 = line1[0][2],sum([i[2] for i in line2 if not np.isnan(i[2])])/2,sum([i[2] for i in line3 if not np.isnan(i[2])])/3\n",
    "    \n",
    "    if (r1 > r2 and r1 > r3 ) or (r1 > 0.8) or (max(df.tb)-min(df.tb) < 0.6):\n",
    "        k,b,r,p = line1[0]\n",
    "        return {'k_list': \n",
    "                  [{'k':k, 'b': b, 'r': r, 'p':p,'type': 'normal'}],\n",
    "                  'writel': {0: (0, 30), 1: (0, 30), 2: (0, 30)}}\n",
    "    if r2 > r3 and r2 > r1:\n",
    "        k1,b1,r1,p1 = line2[0]\n",
    "        k2,b2,r2,p2 = line2[1]\n",
    "        return {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},],\n",
    "                  'writel': {0: (0, cr1[0]), 1: (cr1[0], 30), 2: (0, 30)}}\n",
    "    \n",
    "    k1,b1,r1,p1 = line3[0]\n",
    "    k2,b2,r2,p2 = line3[1]    \n",
    "    k3,b3,r3,p3 = line3[2]  \n",
    "    return {'k_list': \n",
    "                  [{'k':k1, 'b': b1, 'r': r1, 'p':p1,'type': 'normal'},\n",
    "                   {'k':k2, 'b': b2, 'r': r2, 'p':p2,'type': 'normal'},\n",
    "                   {'k':k3, 'b': b3, 'r': r3, 'p':p3,'type': 'normal'},],\n",
    "                  'writel': {0: (0, cr1[0]), 1: (cr1[0], cr2[0]), 2: (cr2[0], 30)}}\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "def piecewise2(x, x0, y0, k1, k2):\n",
    "    return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0])\n",
    "\n",
    "def piecewise3(x,x0,x1,y0,y1,k0,k1):\n",
    "    return np.piecewise(x , [x <= x0, np.logical_and(x0<x, x<= x1),x>x1] ,\n",
    "                        [lambda x:k0*(x-x0) + y0,#根据点斜式构建函数\n",
    "                         lambda x:(x-x0)*(y1-y0)/(x1-x0)+y0,#根据两点式构建函数\n",
    "                        lambda x:k1*(x-x1) + y1])\n",
    "\n",
    "def get_2_line(x,y):\n",
    "    perr_min = np.inf\n",
    "    p_best = None\n",
    "    for n in range(100):\n",
    "        k = np.random.rand(4)*20\n",
    "        try:\n",
    "            p,e = optimize.curve_fit(piecewise2, x, y,p0=k)\n",
    "        except:\n",
    "            continue\n",
    "        perr = np.sum(np.abs(y-piecewise2(x, *p)))\n",
    "        if(perr < perr_min):\n",
    "            perr_min = perr\n",
    "            p_best = p\n",
    "    x0, y0, k1, k2 = p_best\n",
    "    k1,b1,k2,b2 = k1,y0-k1*x0,k2,y0-k2*x0\n",
    "    x1,x2,y1,y2 = [],[],[],[]\n",
    "    \n",
    "    crossx,crossy = (b1-b2)/(k2-k1) , ((b1-b2)/(k2-k1)) *k1 + b1\n",
    "    for i in range(len(x)):\n",
    "        if x[i] < crossx:\n",
    "            x1.append(x[i])\n",
    "            y1.append(y[i])\n",
    "        else:\n",
    "            x2.append(x[i])\n",
    "            y2.append(y[i])\n",
    "    \n",
    "    return [[k1,b1,abs(np.corrcoef(x1,y1)[0][1])],[k2,b2,abs(np.corrcoef(x2,y2)[0][1])]],(crossx,crossy)\n",
    "\n",
    "\n",
    "def get_3_line(x,y):\n",
    "    perr_min = np.inf\n",
    "    p_best = None\n",
    "    for n in range(100):\n",
    "        k = np.random.rand(6)*20\n",
    "        try:\n",
    "            p,e = optimize.curve_fit(piecewise3, x, y,p0=k)\n",
    "        except:\n",
    "            continue\n",
    "        perr = np.sum(np.abs(y-piecewise3(x, *p)))\n",
    "        if(perr < perr_min):\n",
    "            perr_min = perr\n",
    "            p_best = p\n",
    "\n",
    "    x0,x1,y0,y1,k0,k1= p_best\n",
    "    k1,b1,k2,b2,k3,b3 = (k0,y0-k0*x0,\n",
    "                         (y1-y0)/(x1-x0),y0-x0*(y1-y0)/(x1-x0),\n",
    "                          k1,y1-k1*x1)\n",
    "    \n",
    "    x1,x2,x3,y1,y2,y3 = [],[],[],[],[],[]\n",
    "    \n",
    "    crossx1,crossy1 = (b1-b2)/(k2-k1) , ((b1-b2)/(k2-k1)) *k1 + b1\n",
    "    crossx2,crossy2 = (b3-b2)/(k2-k3) , ((b3-b2)/(k2-k3)) *k3 + b3\n",
    "\n",
    "    for i in range(len(x)):\n",
    "        if x[i] < crossx1:\n",
    "            x1.append(x[i])\n",
    "            y1.append(y[i])\n",
    "        elif x[i] < crossx2:\n",
    "            x2.append(x[i])\n",
    "            y2.append(y[i])\n",
    "        else:\n",
    "            x3.append(x[i])\n",
    "            y3.append(y[i])   \n",
    "            \n",
    "    return [[k1,b1,abs(np.corrcoef(x1,y1)[0][1])],[k2,b2,abs(np.corrcoef(x2,y2)[0][1])],[k3,b3,abs(np.corrcoef(x3,y3)[0][1])]],(crossx1,crossy1),(crossx2,crossy2)\n",
    "\n",
    "def svg_to_emf(svg_figpath):\n",
    "    '''1. 如果是.svg的绝对路径，True改为False；\n",
    "       2. inlscape.exe的文件路径中必须是双斜杠\\\\，单斜杠\\会出错；\n",
    "       3. subprocess.call中的shell=True不可省略，否则会报错。'''\n",
    "\n",
    "    if svg_figpath is not None:\n",
    "        path, svgfigname = os.path.split(svg_figpath)\n",
    "        figname, figform = os.path.splitext(svgfigname)\n",
    "        emf_figpath = os.path.join(path, figname + '.emf')\n",
    "        #print(\"{} {} -T -o {}\".format(inkscape_path, svg_figpath, emf_figpath))\n",
    "        return subprocess.call(\"{} {} -T -o {}\".format(inkscape_path, svg_figpath, emf_figpath),shell = True)\n",
    "        # os.remove(svg_figpath)\n",
    "\n",
    "def read_csv2(tb,E):\n",
    "\n",
    "    tb = np.array(tb)\n",
    "    E = np.array(E)\n",
    "\n",
    "\n",
    "    if min(E)>-5.893*2.4987/2 *5:\n",
    "        a = -5.893*2.4987/2 *5 \n",
    "    elif min(E)>-5.893*2.4987/2 *25:\n",
    "        a = -5.893*2.4987/2 *25\n",
    "    else:\n",
    "        a = -5.893*2.4987/2 *35\n",
    "    if max(E) <= 5.893*2.4987/2 *5 :\n",
    "        if min(E)>-5.893*2.4987/2 *25:\n",
    "            a = -5.893*2.4987/2 *25\n",
    "        else:\n",
    "            a = -5.893*2.4987/2 *35\n",
    "        b = 5.893*2.4987/2 *5\n",
    "        sign_loc = 'lower right'\n",
    "    elif max(E) < 5.893*2.4987/2 *35:\n",
    "        b = 5.893*2.4987/2 *35\n",
    "        sign_loc = loc\n",
    "    elif  max(E) < 5.893*2.4987/2 *75:\n",
    "        b = 5.893*2.4987/2 *75\n",
    "        sign_loc = loc\n",
    "    elif  max(E) < 5.893*2.4987/2 *115:\n",
    "        b = 5.893*2.4987/2 *115\n",
    "        sign_loc = loc\n",
    "    elif max(E) < 5.893*2.4987/2 *175:\n",
    "        b = 5.893*2.4987/2 *175\n",
    "        sign_loc = loc\n",
    "    return tb,E,(a,b),round((b-a)/(5.893*2.4987/2)/10),sign_loc\n",
    "    a = \"\"\"   \n",
    "    if max(E)-min(E) <= 5.893*2.4987*20:\n",
    "        a = min(E) - 5.893*2.4987*10+(max(E)-min(E))/2    \n",
    "        b = max(E) + 5.893*2.4987*10-(max(E)-min(E))/2\n",
    "        a = a - a%(5.893*2.4987/2) - (5.893*2.4987/2)\n",
    "        b = b - b%(5.893*2.4987/2) + (5.893*2.4987/2)\n",
    "        return tb,E,type_dict, (a,b),2\n",
    "    else:\n",
    "        slim = int((max(E)-min(E))/(5.893*2.4987*10))\n",
    "        return tb,E,type_dict, (min(E)-(5.893*2.4987*10),max(E)+(5.893*2.4987*10)),slim+2\"\"\"\n",
    "    ''\n",
    "def read_csv(file_path):\n",
    "    with open(file_path,encoding=\"utf-8\") as f:\n",
    "        csv_reader = csv.reader(f)\n",
    "        tb = []\n",
    "        E = []\n",
    "        type_dict = collections.defaultdict(list)\n",
    "        for ri,row in enumerate(csv_reader):\n",
    "            if ri == 0:\n",
    "                continue\n",
    "            tb.append(float(row[0]))\n",
    "            E.append(float(row[1]))\n",
    "\n",
    "            row_total = sum([float(i) for i in row[2:]])\n",
    "            for i,num in enumerate(row[2:]):\n",
    "                type_dict[i+1].append(float(num)/row_total)\n",
    "    \n",
    "    \n",
    "    tb = np.array(tb)\n",
    "    E = np.array(E)\n",
    "    for i in type_dict[i]:\n",
    "        type_dict[i] = np.array(type_dict[i])\n",
    "\n",
    "    tb = tb - 0.5/2   #调整到各\"自中心点\n",
    "    E = E - (5.893*2.4987*0.5)/2\n",
    "    \n",
    "    \n",
    "    if min(E)>-5.893*2.4987/2 *5:\n",
    "        a = -5.893*2.4987/2 *5 \n",
    "    elif min(E)>-5.893*2.4987/2 *25:\n",
    "        a = -5.893*2.4987/2 *25\n",
    "    else:\n",
    "        a = -5.893*2.4987/2 *35\n",
    "    if max(E) <= 5.893*2.4987/2 *5 :\n",
    "        if min(E)>-5.893*2.4987/2 *25:\n",
    "            a = -5.893*2.4987/2 *25\n",
    "        else:\n",
    "            a = -5.893*2.4987/2 *35\n",
    "        b = 5.893*2.4987/2 *5\n",
    "        sign_loc = 'lower right'\n",
    "    elif max(E) < 5.893*2.4987/2 *35:\n",
    "        b = 5.893*2.4987/2 *35\n",
    "        sign_loc = loc\n",
    "    elif  max(E) < 5.893*2.4987/2 *75:\n",
    "        b = 5.893*2.4987/2 *75\n",
    "        sign_loc = loc\n",
    "    elif  max(E) < 5.893*2.4987/2 *115:\n",
    "        b = 5.893*2.4987/2 *115\n",
    "        sign_loc = loc\n",
    "    elif max(E) < 5.893*2.4987/2 *175:\n",
    "        b = 5.893*2.4987/2 *175\n",
    "        sign_loc = loc\n",
    "    return tb,E,type_dict, (a,b),round((b-a)/(5.893*2.4987/2)/10),sign_loc\n",
    "    a = \"\"\"   \n",
    "    if max(E)-min(E) <= 5.893*2.4987*20:\n",
    "        a = min(E) - 5.893*2.4987*10+(max(E)-min(E))/2    \n",
    "        b = max(E) + 5.893*2.4987*10-(max(E)-min(E))/2\n",
    "        a = a - a%(5.893*2.4987/2) - (5.893*2.4987/2)\n",
    "        b = b - b%(5.893*2.4987/2) + (5.893*2.4987/2)\n",
    "        return tb,E,type_dict, (a,b),2\n",
    "    else:\n",
    "        slim = int((max(E)-min(E))/(5.893*2.4987*10))\n",
    "        return tb,E,type_dict, (min(E)-(5.893*2.4987*10),max(E)+(5.893*2.4987*10)),slim+2\"\"\"\n",
    "    \n",
    "    \n",
    "\n",
    "class LatticeImage:\n",
    "    def __init__(self,csv_path,title,tb_ratio,tb,E):\n",
    "        self.color = [\"y\",'r','darkorchid','g','b','fuchsia','limegreen','lightseagreen','chocolate','deepskyblue','y','#990033','#FF9966','#996699','#FF99CC','#999900','#50616d']\n",
    "        #self.color = [\"r\" for i in self.color]\n",
    "        self.color_dict = {\n",
    "            \"森林\" :\"#0000FF\",\n",
    "            \"高山植被\" :\"#32cd32\",\n",
    "            \"沼泽\" :\"#804000\",\n",
    "            \"草丛\" :\"#FFA500\",\n",
    "            \"灌丛\" :\"#007f00\",\n",
    "            \"草原\" :\"#DC143C\",\n",
    "            \"草甸\" :\"#800080\",\n",
    "            \"荒漠\" :\"#ff00ff\",\n",
    "            }\n",
    "        self.title = title\n",
    "        self.markerstyle = '.'\n",
    "        \n",
    "        self.tb2,self.E2,y_range,yy2,self.sign_loc= read_csv2(tb,E)\n",
    "        \n",
    "        self.tb,self.E,self.type_dict,y_range2,yy,self.sign_loc= read_csv(csv_path)\n",
    "        self.type_num = max(self.type_dict.keys())\n",
    "        self.TB_max,self.TB_min,self.E_max,self.E_min = max(self.tb),min(self.tb),max(self.E),min(self.E)\n",
    "        self.yy = yy2\n",
    "        self.fig= plt.subplots(figsize=(12,yy2*2))\n",
    "        self.ax = plt.gca()\n",
    "        self.ax.xaxis.set_ticks_position('bottom')\n",
    "        self.ax.spines['bottom'].set_position(('data', 0))\n",
    "        self.ax.yaxis.set_ticks_position('left')\n",
    "        self.ax.spines['left'].set_position(('data', 0))\n",
    "        self.ax.spines['right'].set_color('none')\n",
    "        self.ax.spines['top'].set_color('none')\n",
    "        \n",
    "        \n",
    "        poly_text2 = '分区界限'\n",
    "        for i in [2,6,10,14,22]:\n",
    "            self.ax.axvline(x=i,ls=\"--\",c=\"#000000\",linewidth=1,alpha = 0.5)\n",
    "            \n",
    "        self.ax.xaxis.set_ticks([2,6,10,14,22,30])  \n",
    "        self.ax.plot(np.linspace(0, 30, 5), 4*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,label=poly_text2,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), 2*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), 5.893*2.4987*np.linspace(0, 30, 5), '--k', linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (1/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        #3.4修改： 删除p/pe=3线 self.ax.plot(np.linspace(0, 30, 5), (-1/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (-1/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)    \n",
    "        self.ax.plot(np.linspace(0, 30, 5), -0.5*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (-3/5)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (-2/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), -5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        \n",
    "        \n",
    "        plt.axhline(0, color='k')#第四区线，p=1/2pe\n",
    "        plt.axhline(0, color='k')#\n",
    "\n",
    "        self.ax.xaxis.grid(True, which='minor',linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.xaxis.grid(True,linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.yaxis.grid(True, which='minor',linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.yaxis.grid(True,linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        #self.ax.set_xlabel('TB (℃)',fontproperties =font_set)\n",
    "        self.ax.set_ylabel('E',fontproperties =font_set)\n",
    "        \n",
    "        self.ax.xaxis.set_major_locator(MultipleLocator(5))\n",
    "        self.ax.yaxis.set_major_locator(MultipleLocator(5.893*2.4987*0.5*10))\n",
    "        self.ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))\n",
    "        self.ax.yaxis.set_major_formatter(FormatStrFormatter('%1.1f'))\n",
    "        self.ax.xaxis.set_minor_locator(MultipleLocator(0.5))\n",
    "        self.ax.yaxis.set_minor_locator(MultipleLocator(5.893*2.4987*0.5))\n",
    "        self.ax.set_xlim(0,30.0)  #设置坐标取值范围\n",
    "        self.ax.set_ylim(y_range)\n",
    "        plt.draw()\n",
    "        self.y_ticks = [float(i.get_text()) for i in self.ax.yaxis.get_ticklabels()]\n",
    "        \n",
    "        y_range = (self.y_ticks[0],self.y_ticks[-1])\n",
    "        k = self.y_ticks[-1]/30\n",
    "        k_ = self.y_ticks[0]/30\n",
    "        \n",
    "        if k < (4*5.893*2.4987):\n",
    "            plt.text(y_range[1]/(4*5.893*2.4987)-2,y_range[1]+3,\"pe/p=0.25\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(4*5.893*2.4987),\"pe/p=0.25\",fontproperties = font_set)\n",
    "            \n",
    "        if k < (2*5.893*2.4987):\n",
    "            plt.text(y_range[1]/(2*5.893*2.4987)-0.8,y_range[1]+3,\"pe/p=0.5\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(2*5.893*2.4987),\"pe/p=0.5\",fontproperties = font_set)\n",
    "            \n",
    "        if k < (5.893*2.4987):\n",
    "            plt.text(y_range[1]/(5.893*2.4987)-0.7,y_range[1]+3,\"pe/p=1\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(5.893*2.4987),\"pe/p=1\",fontproperties = font_set)\n",
    "            \n",
    "        if k < (1/3)*5.893*2.4987:\n",
    "            plt.text(y_range[1]/((1/3)*5.893*2.4987)-1,y_range[1]+3,\"pe/p=1.5\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*((1/3)*5.893*2.4987),\"pe/p=1.5\",fontproperties = font_set)     \n",
    "            \n",
    "        plt.text(30,0,\"pe/p=2\\nTB (℃)\",fontproperties = font_set)\n",
    "        \n",
    "        #3.4修改： 删除p/pe=3线\n",
    "        #if k_ > (-1/3)*5.893*2.4987:\n",
    "          #  plt.text(y_range[0]/((-1/3)*5.893*2.4987)-0.7,y_range[0]-3,\"pe/p=3\",fontproperties = font_set)\n",
    "        #else:\n",
    "         #   plt.text(30,30*((-1/3)*5.893*2.4987),\"pe/p=3\",fontproperties = font_set)     \n",
    "        if k_ > -(1/3)*5.893*2.4987:\n",
    "            plt.text(y_range[0]/(-(1/3)*5.893*2.4987)-0.7,y_range[0]-3,\"pe/p=3\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(-(1/3)*5.893*2.4987),\"pe/p=3\",fontproperties = font_set)        \n",
    "        if k_ > -0.5*5.893*2.4987:\n",
    "            plt.text(y_range[0]/(-0.5*5.893*2.4987)-0.3,y_range[0]-3,\"pe/p=4\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(-0.5*5.893*2.4987),\"pe/p=4\",fontproperties = font_set)     \n",
    "        if k_ > -(3/5)*5.893*2.4987:\n",
    "            plt.text(y_range[0]/(-(3/5)*5.893*2.4987)-0.4,y_range[0]-3,\"pe/p=5\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(-(3/5)*5.893*2.4987),\"pe/p=5\",fontproperties = font_set)        \n",
    "        if k_ > -(2/3)*5.893*2.4987:\n",
    "            if y_range[0] > -60:\n",
    "                plt.text(y_range[0]/(-(2/3)*5.893*2.4987)-1.5,y_range[0]-3,\"pe/p=6\",fontproperties = font_set)\n",
    "            else:\n",
    "                plt.text(y_range[0]/(-(2/3)*5.893*2.4987)-0.5,y_range[0]-3,\"pe/p=6\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(-(2/3)*5.893*2.4987),\"pe/p=6\",fontproperties = font_set)        \n",
    "\n",
    "        if k_ > -5.893*2.4987:\n",
    "            plt.text(y_range[0]/(-5.893*2.4987)-0.5,y_range[0]-3,\"p=0\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text(30,30*(-5.893*2.4987),\"p=0\",fontproperties = font_set)     \n",
    "\n",
    "        ###划分界限的标签\n",
    "        ###划百分比\n",
    "        point_set = [(0.5*i,round(j*(5.893*2.4987*0.5),8)) for j in range(int(y_range[0]/(5.893*2.4987*0.5)),int(y_range[1]/(5.893*2.4987*0.5))) for i in range(0,60)]\n",
    "        tb_e = [(self.tb[i]-0.25,round(self.E[i]-(5.893*2.4987*0.5)/2,8)) for i in range(len(self.tb))]\n",
    "        valid_point_set = list(set(point_set) - set(tb_e))\n",
    "        self.q = point_set\n",
    "        self.p = tb_e\n",
    "        area_dict = {}\n",
    "        area_dict_default = {}\n",
    "        \n",
    "        for i in range(12):\n",
    "            for j in range(7):\n",
    "                area_dict[(i,j)] = []\n",
    "                area_dict_default[(i,j)] = []\n",
    "        area_dict_default[(5,0)] = [[5.5,1]]     \n",
    "        for xy in point_set :\n",
    "            x,y = xy[0],xy[1]\n",
    "            if y>  4*5.893*2.4987* x: a = 0\n",
    "            elif y>  2*5.893*2.4987* x: a = 1\n",
    "            elif y >  5.893*2.4987* x: a = 2\n",
    "            elif y >  (1/3)*5.893*2.4987* x : a = 3    \n",
    "            elif y >= 0: a = 4\n",
    "            elif y >  -(1/3)*5.893*2.4987* x : a = 5\n",
    "            elif y >=  -0.5*5.893*2.4987* x: a = 6\n",
    "            elif y >  -(3/5)*5.893*2.4987* x : a = 7  \n",
    "            elif y >  -(2/3)*5.893*2.4987* x : a = 8  \n",
    "            elif y >=  -5.893*2.4987* x: a = 9\n",
    "            else : a = 10\n",
    "                \n",
    "                \n",
    "            if x <2: b = 0\n",
    "            elif x<6: b = 1\n",
    "            elif x<10: b = 2\n",
    "            elif x<14: b = 3\n",
    "            elif x<22: b = 4\n",
    "            elif x<30: b = 5\n",
    "            area_dict_default[(a,b)].append(xy)\n",
    "                \n",
    "        for xy in valid_point_set :\n",
    "            x,y = xy[0],xy[1]\n",
    "            if y>  4*5.893*2.4987* x: a = 0\n",
    "            elif y>  2*5.893*2.4987* x: a = 1\n",
    "            elif y >  5.893*2.4987* x: a = 2\n",
    "            elif y >  (1/3)*5.893*2.4987* x : a = 3    \n",
    "            elif y >= 0: a = 4\n",
    "            elif y >  -(1/3)*5.893*2.4987* x : a = 5\n",
    "            elif y >=  -0.5*5.893*2.4987* x: a = 6\n",
    "            elif y >  -(3/5)*5.893*2.4987* x : a = 7  \n",
    "            elif y >  -(2/3)*5.893*2.4987* x : a = 8  \n",
    "            elif y >=  -5.893*2.4987* x: a = 9\n",
    "            else : a = 10\n",
    "                \n",
    "                \n",
    "            if x <2: b = 0\n",
    "            elif x<6: b = 1\n",
    "            elif x<10: b = 2\n",
    "            elif x<14: b = 3\n",
    "            elif x<22: b = 4\n",
    "            elif x<30: b = 5\n",
    "            area_dict[(a,b)].append(xy)\n",
    "        self.r3 = tb_ratio\n",
    "        self.r4 = area_dict\n",
    "        self.r5 = area_dict_default\n",
    "        def get_text_location(x,y):\n",
    "            point_list = area_dict[(x,y)]\n",
    "            if not point_list:\n",
    "                point_list = area_dict_default[(x,y)]\n",
    "                return sum([i[0] for i in point_list])/len(point_list),sum([i[1] for i in point_list])/len(point_list)\n",
    "            mean_x = sum([i[0] for i in point_list])/len(point_list)\n",
    "            mean_y = sum([i[1] for i in point_list])/len(point_list)\n",
    "            point_list.sort(key = lambda x : (x[0] - mean_x)**2 + (x[1] - mean_y)**2 )\n",
    "            for i in point_list:\n",
    "                if (i[0]+0.5,i[1]) in point_list:\n",
    "                    return i[0],i[1]\n",
    "\n",
    "            point_list = area_dict_default[(x,y)]\n",
    "            return sum([i[0] for i in point_list])/len(point_list),sum([i[1] for i in point_list])/len(point_list)\n",
    "            \n",
    "        \n",
    "        for i in range(12):\n",
    "            for j in range(7):\n",
    "                if tb_ratio[i][j] != 0 :\n",
    "                    #for e in area_dict[(i,j)]:\n",
    "                       # plt.text(e[0],e[1],str(10*i+j),fontproperties = font_set_2)\n",
    "                    x,y = get_text_location(i,j)\n",
    "                    plt.text(x,y,\"%.2f\"%(tb_ratio[i][j]*100) +\"%\",fontproperties = font_set_2)\n",
    "        \n",
    "        \n",
    "        self.name_dict = {'0': ['森林', 0], '1': ['灌丛', 1], '2': ['草丛', 2], '3': ['草原', 3], '4': ['荒漠', 4], '5': ['草甸', 5], '6': ['沼泽', 6], '7': ['高山植被', 7], '8': ['栽培植被', 8]}\n",
    "        \n",
    "           \n",
    "    def set_color_and_mark(self,color_dict = dict , mark = \".\" ):\n",
    "        self.color_dict = color_dict \n",
    "        self.markerstyle = mark\n",
    "        \n",
    "\n",
    "    def get_xy(self,columns):\n",
    "        index_dict = collections.defaultdict(list)\n",
    "        type_dict_final = type_dict_import\n",
    "        type_index_list = [[] for i in range(9)]\n",
    "        for num,i in enumerate(columns[2:]):\n",
    "            if str(int(i)) in type_dict_final:\n",
    "                type_index_list[type_dict_final[str(int(i))]] .append(num)\n",
    "\n",
    "        new_type_dict = {}\n",
    "        for i in range(1,10):\n",
    "            new_type_dict[i] = [sum([self.type_dict[index+1][j] for index in type_index_list[i-1]]) for j in range(len(self.type_dict[1]))]\n",
    "\n",
    "        self.type_dict  = new_type_dict \n",
    "        columns = [\"\",\"\",] + [str(i+1) for i in range(9)]\n",
    "        for i in range(1,10):\n",
    "            for index,ratio in enumerate(self.type_dict[i]):\n",
    "                if not index_dict[(self.tb[index],self.E[index])]:\n",
    "                    index_dict[(self.tb[index],self.E[index])] = [[],[],[]]\n",
    "\n",
    "                if ratio >= 0.6321:\n",
    "                    index_dict[(self.tb[index],self.E[index])][0].append(str(columns[i+1]))\n",
    "                elif ratio >= 0.3679:\n",
    "                    index_dict[(self.tb[index],self.E[index])][1].append(str(columns[i+1]))\n",
    "                else:\n",
    "                    index_dict[(self.tb[index],self.E[index])][2].append(str(columns[i+1]))\n",
    "\n",
    "        return index_dict\n",
    "    \n",
    "    \n",
    "    def generate_image(self,save_path,columns,line_list,csv_df,max_limit,ii,sign):  \n",
    "        ii = int(ii)\n",
    "        writel = line_list[\"writel\"] \n",
    "        line_list = line_list[\"k_list\"] \n",
    "        index_dict = self.get_xy(columns)\n",
    "        write_dict = collections.defaultdict(list)\n",
    "        for i in index_dict:\n",
    "            if index_dict[i][0]:\n",
    "                write_dict[(tuple(set(index_dict[i][0])),tuple(set(index_dict[i][2])),0)].append(i)\n",
    "            else:\n",
    "                write_dict[(tuple(set(index_dict[i][1])),tuple(set(index_dict[i][2])),1)].append(i)\n",
    "        columns = [\"\",\"\",] + [str(i+1) for i in range(9)]\n",
    "\n",
    "        x = np.linspace(0,max_limit,100)    \n",
    "\n",
    "        \n",
    "        #self.ax.plot(np.mean(csv_nif.tb),np.mean(csv_df.E_sum),\"o\",markersize =1,alpha = 1,c=\"#000000\",label = \"均值点\")\n",
    "        self.ax.axvline(x=np.mean(csv_df.tb),ls=\"--\",c=\"r\",linewidth=0.5,alpha = 0.5)\n",
    "        self.ax.axhline(y=np.mean(csv_df.E_sum),ls=\"--\",c=\"r\",linewidth=0.5,alpha = 0.5)\n",
    "        \n",
    "        ticks = [0,2,6,10,14,22,30]\n",
    "        \n",
    "        self.ax.xaxis.set_ticks(sorted(ticks+ [np.mean(csv_df.tb)]))\n",
    "        self.ax.xaxis.set_ticklabels(sorted(ticks +[round(float(np.mean(csv_df.tb)),2)]))\n",
    "        \n",
    "        red_x = sorted(ticks+ [round(float(np.mean(csv_df.tb)),2)]).index(round(float(np.mean(csv_df.tb)),2))\n",
    "        self.ax.xaxis.get_ticklabels()[red_x].set_color(\"red\")\n",
    "        self.ax.xaxis.get_ticklabels()[red_x].set_alpha(0)\n",
    "        #画线 y范围变动 没写完\n",
    "        ticks = self.y_ticks\n",
    "        is_delete_y_label = -1\n",
    "        if is_delete_y_label >= 0:\n",
    "            ticks[is_delete_y_label] = round(float(np.mean(csv_df.E_sum)),2)\n",
    "            self.ax.yaxis.set_ticks(ticks)\n",
    "            self.ax.yaxis.set_ticklabels(ticks)\n",
    "            red_y = ticks.index(round(float(np.mean(csv_df.E_sum)),2))\n",
    "        else:\n",
    "            self.ax.yaxis.set_ticks(sorted(ticks+ [np.mean(csv_df.E_sum)]))\n",
    "            ticks =  sorted(ticks +[round(float(np.mean(csv_df.E_sum)),2)])\n",
    "            ticklabels = ticks\n",
    "            self.ax.yaxis.set_ticklabels(ticklabels)\n",
    "            red_y = ticks.index(round(float(np.mean(csv_df.E_sum)),2))\n",
    "        \n",
    "        self.ax.yaxis.get_ticklabels()[red_y].set_color(\"red\")\n",
    "        self.ax.yaxis.get_ticklabels()[red_y].set_alpha(0)\n",
    "\n",
    "        plt.legend(prop = font_set,loc = loc)\n",
    "        \n",
    "        temp_store_index = []\n",
    "        for key in write_dict:\n",
    "            if not key[2]:\n",
    "                temp_store_index.append(key)\n",
    "        temp_store_index.sort(key = lambda x: x[0])    \n",
    "        \n",
    "        for key in temp_store_index:\n",
    "            priority = [self.name_dict[str(int(i)-1)] for i in key[0]]\n",
    "            priority.sort(key = lambda x : x[1])\n",
    "            priority = [i[0] for i in priority] \n",
    "            \n",
    "            color = self.color_dict[priority[0]]\n",
    "            \n",
    "            if key[1]:\n",
    "                crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]\n",
    "                crisscross.sort(key = lambda x : x[1])\n",
    "                crisscross = [i[0] for i in crisscross]\n",
    "                label = \"稳态：  \" + \",\".join(i for i in priority)# + \"\\n混沌态：\" + \",\".join(i for i in crisscross if i != \"栽培植被\")\n",
    "            else:\n",
    "                label = \"稳态：  \" + \",\".join(i for i in priority)\n",
    "            self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], \".\", markerfacecolor='white',color=color, markersize = 12,label=label,markeredgecolor=color,markeredgewidth=0.8)\n",
    "            plt.legend(prop = font_set,loc = loc)    \n",
    "   \n",
    "\n",
    "\n",
    "        temp_store_index = []    \n",
    "        for key in write_dict:\n",
    "            if key[2] and key[0]: \n",
    "                temp_store_index.append(key)\n",
    "        temp_store_index.sort(key = lambda x: x[0])            \n",
    "\n",
    "        for key in temp_store_index:     \n",
    "            if len(key[0]) == 1:\n",
    "                \n",
    "                priority = [self.name_dict[str(int(i)-1)] for i in key[0]]\n",
    "                priority.sort(key = lambda x : x[1])\n",
    "                priority = [i[0] for i in priority]\n",
    "                color = self.color_dict[priority[0]]\n",
    "                if key[1]:\n",
    "                    crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]\n",
    "                    crisscross.sort(key = lambda x : x[1])\n",
    "                    crisscross = [i[0] for i in crisscross]\n",
    "                    label = \"亚稳态：\" + \",\".join(i for i in priority) #+ \"\\n混沌态：\" +\",\".join(i for i in crisscross if i != \"栽培植被\")\n",
    "                else:\n",
    "                    label = \"亚稳态：\" + \",\".join(i for i in priority)\n",
    "                #label = \",\".join(self.name_dict[i] for i in key[0]) +\"为优势，和\" + \",\".join(self.name_dict[i] for i in key[1]) +\"的交错类型\"\n",
    "                #pattern = re.compile('.{30}')\n",
    "                #label = '\\n'.join(pattern.findall(label)) + \"\\n\" + label[-(len(label)%30):]\n",
    "                self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], \"^\", color=color, markerfacecolor='white',markersize = 6,label=label,markeredgecolor=color,markeredgewidth=0.8)\n",
    "                plt.legend(prop = font_set,loc = loc)\n",
    "\n",
    "                \n",
    "        for key in temp_store_index:     \n",
    "            if len(key[0]) == 2:\n",
    "                priority = [self.name_dict[str(int(i)-1)] for i in key[0]]\n",
    "                priority.sort(key = lambda x : x[1])\n",
    "                priority = [i[0] for i in priority]\n",
    "                color = self.color_dict[priority[0]]\n",
    "                if key[1]:\n",
    "                    \n",
    "                    crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]\n",
    "                    crisscross.sort(key = lambda x : x[1])\n",
    "                    crisscross = [i[0] for i in crisscross]\n",
    "                    label = \"亚稳态：\" + \",\".join(i for i in priority) #+ \"\\n混沌态：\" +\",\".join(i for i in crisscross if i != \"栽培植被\")\n",
    "                else:\n",
    "                    label = \"亚稳态：\" + \",\".join(i for i in priority)\n",
    "                #label = \",\".join(self.name_dict[i] for i in key[0]) +\"为优势，和\" + \",\".join(self.name_dict[i] for i in key[1]) +\"的交错类型\"\n",
    "                #pattern = re.compile('.{30}')\n",
    "                #label = '\\n'.join(pattern.findall(label)) + \"\\n\" + label[-(len(label)%30):]\n",
    "                self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], \"s\", color=color, markerfacecolor='white',markersize = 6,label=label,markeredgecolor=color,markeredgewidth=0.8)\n",
    "                plt.legend(prop = font_set,loc = loc)\n",
    "\n",
    "        \n",
    "        temp_store_index = []   \n",
    "        for key in write_dict:\n",
    "            if key[2] and not key[0] and key[1]:\n",
    "                temp_store_index.append(key)\n",
    "        temp_store_index.sort(key = lambda x: x[1])            \n",
    "        for key in temp_store_index:     \n",
    "\n",
    "            crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]\n",
    "            crisscross.sort(key = lambda x : x[1])\n",
    "            crisscross = [i[0] for i in crisscross]\n",
    "\n",
    "            color = self.color_dict[crisscross[0]]\n",
    "            label = \"混沌态\" #+ \",\".join(i for i in crisscross if i != \"栽培植被\")\n",
    "            #pattern = re.compile('.{30}')\n",
    "            #label = \",\".join(self.name_dict[i] for i in key[1]) +\"交错类型\"\n",
    "            #label = '\\n'.join(pattern.findall(label)) + \"\\n\" + label[-(len(label)%30):]\n",
    "            self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], \"D\", markerfacecolor='white',color=\"#FFFF00\", markersize = 4,label=label,markeredgecolor=\"#FFFF00\",markeredgewidth=0.8)\n",
    "            plt.legend(prop = font_set,loc = loc) \n",
    "\n",
    "\n",
    "        self.ax.scatter(csv_df.tb,csv_df.E_sum,2,alpha =0.5,c=self.color[ii%16],zorder=2,label = save_path.split(\"\\\\\")[-1][:-4])\n",
    "        \n",
    "        self.ax.scatter(np.mean(csv_df.tb),np.mean(csv_df.E_sum),1,marker = \"o\",c=\"#000000\",zorder=3,label = \"均值点\"+\"(%s,%s)\"%(round(np.mean(csv_df.tb),2),round(np.mean(csv_df.E_sum),2)))\n",
    "        \n",
    "        if not sign:\n",
    "            for index,i in enumerate(line_list):\n",
    "                k,b,r2,typei = i[\"k\"],i[\"b\"],i[\"r\"],i[\"type\"]\n",
    "                if typei == \"none\":\n",
    "                        pass\n",
    "                elif typei == \"vertical\":\n",
    "                    plt.vlines(k,-200,888,colors=self.color[ii%16], label = \"TB=%.2f\"%k,linewidth=0.6 )\n",
    "                elif typei == \"up_vertical\":\n",
    "                    plt.vlines(k,b,888,colors=self.color[ii%16], label = \"TB=%.2f\"%k,linewidth=0.6 )\n",
    "                elif typei == \"down_vertical\":\n",
    "                    plt.vlines(k,-200,b,colors=self.color[ii%16], label = \"TB=%.2f\"%k,linewidth=0.6 )\n",
    "                elif typei == \"horizon\":\n",
    "                        x = np.linspace(writel[index][0],writel[index][1],100)   \n",
    "                        plt.plot(x,k*x+b ,c=\"#990000\",label = \"E=%.2f\"%b,linewidth=0.6 )\n",
    "                else:\n",
    "                    x = np.linspace(writel[index][0],writel[index][1],100)    \n",
    "                    plt.plot(x,k*x+b , c=\"#990000\",label = \"E=%.2f*TB+%.2f(R²=%.2f)\"%(k,b,r2),linewidth=0.6 )\n",
    "\n",
    "\n",
    "        plt.legend(prop = font_set,loc = loc)\n",
    "        plt.savefig(save_path, dpi = 900,bbox_inches='tight')\n",
    "        svg_to_emf(save_path)\n",
    "        plt.clf()\n",
    "        plt.close()\n",
    "        \n",
    "\n",
    "        \n",
    "        \n",
    "        \n",
    "class LatticeImageForAll:\n",
    "    def __init__(self,tb,E,title,keyl):\n",
    "        self.key = keyl\n",
    "        self.color = [\"y\",'r','darkorchid','g','b','fuchsia','limegreen','lightseagreen','chocolate','deepskyblue','y','#990033','#FF9966','#996699','#FF99CC','#999900','#50616d']\n",
    "        self.color_dict = {\n",
    "            \"森林\" :\"#0000FF\",\n",
    "            \"高山植被\" :\"#32cd32\",\n",
    "            \"沼泽\" :\"#804000\",\n",
    "            \"草丛\" :\"#FFA500\",\n",
    "            \"灌丛\" :\"#007f00\",\n",
    "            \"草原\" :\"#DC143C\",\n",
    "            \"草甸\" :\"#800080\",\n",
    "            \"荒漠\" :\"#ff00ff\",\n",
    "            }\n",
    "        self.title = title\n",
    "        self.markerstyle = '.'\n",
    "        \n",
    "\n",
    "        if min(E)>-5.893*2.4987/2 *5:\n",
    "            a = -5.893*2.4987/2 *5 \n",
    "        elif min(E)>-5.893*2.4987/2 *25:\n",
    "            a = -5.893*2.4987/2 *25\n",
    "        else:\n",
    "            a = -5.893*2.4987/2 *35\n",
    "        if max(E) <= 5.893*2.4987/2 *5 :\n",
    "            if min(E)>-5.893*2.4987/2 *25:\n",
    "                a = -5.893*2.4987/2 *25\n",
    "            else:\n",
    "                a = -5.893*2.4987/2 *35\n",
    "            b = 5.893*2.4987/2 *5\n",
    "            sign_loc = 'lower right'\n",
    "        elif max(E) < 5.893*2.4987/2 *35:\n",
    "            b = 5.893*2.4987/2 *35\n",
    "            sign_loc = loc\n",
    "        elif  max(E) < 5.893*2.4987/2 *75:\n",
    "            b = 5.893*2.4987/2 *75\n",
    "            sign_loc = loc\n",
    "        elif  max(E) < 5.893*2.4987/2 *115:\n",
    "            b = 5.893*2.4987/2 *115\n",
    "            sign_loc = loc\n",
    "        elif max(E) < 5.893*2.4987/2 *175:\n",
    "            b = 5.893*2.4987/2 *175\n",
    "            sign_loc = loc\n",
    "        self.tb,self.E,y_range,yy,self.sign_loc = tb,E,(a,b),round((b-a)/(5.893*2.4987/2)/7),sign_loc\n",
    "\n",
    "        self.TB_max,self.TB_min,self.E_max,self.E_min = max(self.tb),min(self.tb),max(self.E),min(self.E)\n",
    "        self.yy = yy\n",
    "        self.fig= plt.subplots(figsize=(12,yy*2))\n",
    "        self.ax = plt.gca()\n",
    "        self.ax.xaxis.set_ticks_position('bottom')\n",
    "        self.ax.spines['bottom'].set_position(('data', 0))\n",
    "        self.ax.yaxis.set_ticks_position('left')\n",
    "        self.ax.spines['left'].set_position(('data', 0))\n",
    "        self.ax.spines['right'].set_color('none')\n",
    "        self.ax.spines['top'].set_color('none')\n",
    "        \n",
    "\n",
    "        \n",
    "        poly_text2 = '分区界限'\n",
    "        for i in [2,6,10,14,22]:\n",
    "            self.ax.axvline(x=i,ls=\"--\",c=\"#000000\",linewidth=1,alpha = 0.5)\n",
    "            \n",
    "        self.ax.xaxis.set_ticks([2,6,10,14,22,30])  \n",
    "        self.ax.plot(np.linspace(0, 30, 5), 4*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,label=poly_text2,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), 2*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), 5.893*2.4987*np.linspace(0, 30, 5), '--k', linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (1/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        #3.4修改： 删除p/pe=3线 self.ax.plot(np.linspace(0, 30, 5), (-1/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (-1/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)    \n",
    "        self.ax.plot(np.linspace(0, 30, 5), -0.5*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (-3/5)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), (-2/3)*5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        self.ax.plot(np.linspace(0, 30, 5), -5.893*2.4987*np.linspace(0, 30, 5), '--k',linewidth=1,alpha = 0.5)\n",
    "        \n",
    "        \n",
    "        plt.axhline(0, color='k')#第四区线，p=1/2pe\n",
    "        plt.axhline(0, color='k')# \n",
    "        self.ax.xaxis.grid(True, which='minor',linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.xaxis.grid(True,linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.yaxis.grid(True, which='minor',linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.yaxis.grid(True,linestyle='--', linewidth=0.5,alpha=0.3)\n",
    "        self.ax.set_xlabel('TB (℃)',fontproperties =font_set)\n",
    "        self.ax.set_ylabel('E',fontproperties =font_set)\n",
    "        \n",
    "        self.ax.xaxis.set_major_locator(MultipleLocator(5))\n",
    "        self.ax.yaxis.set_major_locator(MultipleLocator(5.893*2.4987*0.5*5))\n",
    "        self.ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))\n",
    "        self.ax.yaxis.set_major_formatter(FormatStrFormatter('%1.1f'))\n",
    "        self.ax.xaxis.set_minor_locator(MultipleLocator(0.5))\n",
    "        self.ax.yaxis.set_minor_locator(MultipleLocator(5.893*2.4987*0.5))\n",
    "        \n",
    "        ticks = [0,2,6,10,14,22,30]\n",
    "        yt = [999999,4,2,1,1/3,0,-1/3,-0.5,-3/5,-2/3,-1]\n",
    "\n",
    "        xmin,xmax,ymin,ymax = 999999,-999999,999999,-999999\n",
    "        for key in keyl.split(\",\"):\n",
    "            x,y = int(key[0]),int(key[1:])\n",
    "            x1 = np.linspace(ticks[x-1],ticks[x],100) \n",
    "            y1 = 5.893*2.4987*x1*yt[y-1]\n",
    "            y2 = 5.893*2.4987*x1*yt[y]\n",
    "            \n",
    "            \n",
    "            xmin,xmax,ymin,ymax = min(min(x1),xmin),max(max(x1),xmax),min(min(list(y1) + list(y2)),ymin),max(max(list(y1) + list(y2)),ymax)\n",
    "        if ymax >1000:\n",
    "            ymax = max(E)+ 100\n",
    "        self.ax.xaxis.set_ticks([2,6,10,14,22,30])  \n",
    "        self.ax.set_xlim(0,max(22,xmax)+2)  #设置坐标取值范围\n",
    "        self.xmax = max(22,xmax) + 2\n",
    "        xmax = max(22,xmax)\n",
    "        self.ax.set_ylim(min(ymin,-10)-20,max(ymax,10)+20)\n",
    "\n",
    "        plt.draw()\n",
    "        \n",
    "        self.y_ticks = [float(i.get_text()) for i in self.ax.yaxis.get_ticklabels()]\n",
    "        \n",
    "\n",
    "        k =  (max(ymax,10)+20)/(xmax+2)\n",
    "        k_ = (min(ymin,-10)-20)/(xmax+2)\n",
    "        \n",
    "        y_range = (min(ymin,-10)-20,max(ymax,10)+20)\n",
    "\n",
    "        if k < (4*5.893*2.4987):\n",
    "            plt.text((y_range[1]-15)/(4*5.893*2.4987),y_range[1]+1.5,\"pe/p=0.25\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(4*5.893*2.4987),\"pe/p=0.25\",fontproperties = font_set)\n",
    "\n",
    "        if k < (2*5.893*2.4987):\n",
    "            plt.text((y_range[1])/(2*5.893*2.4987),y_range[1]+1.5,\"pe/p=0.5\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(2*5.893*2.4987),\"pe/p=0.5\",fontproperties = font_set)\n",
    "\n",
    "        if k < (5.893*2.4987):\n",
    "            plt.text((y_range[1])/(5.893*2.4987),y_range[1]+1.5,\"pe/p=1\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(5.893*2.4987),\"pe/p=1\",fontproperties = font_set)\n",
    "\n",
    "        if k < (1/3)*5.893*2.4987:\n",
    "            plt.text((y_range[1])/((1/3)*5.893*2.4987),y_range[1]+1.5,\"pe/p=1.5\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*((1/3)*5.893*2.4987),\"pe/p=1.5\",fontproperties = font_set)     \n",
    "\n",
    "        plt.text((xmax+2),0,\"pe/p=2\",fontproperties = font_set)\n",
    "\n",
    "        \n",
    "        if k_ > -(1/3)*5.893*2.4987:\n",
    "            plt.text((y_range[0])/(-(1/3)*5.893*2.4987),y_range[0]-1.5,\"pe/p=3\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(-(1/3)*5.893*2.4987),\"pe/p=3\",fontproperties = font_set)        \n",
    "        if k_ > -0.5*5.893*2.4987:\n",
    "            plt.text((y_range[0])/(-0.5*5.893*2.4987)+0.5,y_range[0]-1.5,\"pe/p=4\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(-0.5*5.893*2.4987),\"pe/p=4\",fontproperties = font_set)     \n",
    "        if k_ > -(3/5)*5.893*2.4987:\n",
    "            plt.text((y_range[0])/(-(3/5)*5.893*2.4987),y_range[0]-1.5,\"pe/p=5\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(-(3/5)*5.893*2.4987),\"pe/p=5\",fontproperties = font_set)   \n",
    "        if k_ > -(2/3)*5.893*2.4987:\n",
    "            if y_range[0] > -35:\n",
    "                plt.text(y_range[0]/(-(2/3)*5.893*2.4987)-1,y_range[0]-1.5,\"pe/p=6\",fontproperties = font_set)\n",
    "            else:\n",
    "                plt.text((y_range[0])/(-(2/3)*5.893*2.4987),y_range[0]-1.5,\"pe/p=6\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(-(2/3)*5.893*2.4987),\"pe/p=6\",fontproperties = font_set)        \n",
    "\n",
    "        if k_ > -5.893*2.4987:\n",
    "            plt.text((y_range[0]-1.5)/(-5.893*2.4987)-1,y_range[0]-1.5,\"p=0\",fontproperties = font_set)\n",
    "        else:\n",
    "            plt.text((xmax+2),(xmax+2)*(-5.893*2.4987),\"p=0\",fontproperties = font_set) \n",
    "\n",
    "    def generate_image(self,save_path,numbers):  \n",
    "        ticks = [i for i in [0,2,6,10,14,22,30] if i <=self.xmax]\n",
    "        self.ax.xaxis.set_ticks(ticks)\n",
    "        self.ax.xaxis.set_ticklabels(sorted(ticks))\n",
    "        keyl = self.key\n",
    "        ticks = [0,2,6,10,14,22,30]\n",
    "        yt = [999999,4,2,1,1/3,0,-1/3,-0.5,-3/5,-2/3,-1]\n",
    "        ii = 1\n",
    "        self.ax.plot(self.tb,self.E,\"o\",markersize =4,alpha = 1,c=\"#000000\",label = \"均值点\" ,zorder=102)\n",
    "        \n",
    "        \n",
    "        \n",
    "        ban_loc_list = [[self.tb[i],self.E[i]] for i in range(len(self.tb))]\n",
    "\n",
    "\n",
    "        def reject_clash(x,y,banlist):\n",
    "            x1 = (x-0.45,x-0.15)\n",
    "            x2 = (x-0.15,x+0.15)\n",
    "            x3 = (x+0.15,x+0.45)\n",
    "            y1 = (y-2.25,y-0.75)\n",
    "            y2 = (y-0.75,y+0.75)\n",
    "            y3 = (y+0.75,y+2.25)\n",
    "            loc = [\n",
    "                    \"right middle\",\n",
    "                \"right upper\",\n",
    "                    \"right lower\",\n",
    "                    \"middle upper\",\n",
    "                    \"middle lower\",\n",
    "                    \"left upper\",\n",
    "                    \"left middle\",\n",
    "                    \"left lower\"]\n",
    "            u1,u2 = [i[0] for i in ban_loc_list]   , [i[1] for i in ban_loc_list]  \n",
    "            chosen_loc = {\"right upper\" :[x3,y3],\n",
    "                        \"right middle\" :[x3,y2],\n",
    "                        \"right lower\" :[x3,y1],\n",
    "                        \"middle upper\" :[x2,y3],\n",
    "                        \"middle lower\" :[x2,y1],\n",
    "                        \"left upper\" :[x1,y3],\n",
    "                        \"left middle\" :[x1,y2],\n",
    "                        \"left lower\" :[x1,y1]}\n",
    "            \n",
    "            loc_dict = {\"right upper\" :[0.1,1],\n",
    "                        \"right middle\" :[0.1,-0.3],\n",
    "                        \"right lower\" :[0.1,-2.5],\n",
    "                        \"middle upper\" :[-0.1,1],\n",
    "                        \"middle lower\" :[-0.1,-2.5],\n",
    "                        \"left upper\" :[-0.3,1],\n",
    "                        \"left middle\" :[-0.3,-0.3],\n",
    "                        \"left lower\" :[-0.3,-2.5]}\n",
    "            \n",
    "            for i in banlist:\n",
    "                x4,y4 = i\n",
    "                for j in chosen_loc:\n",
    "                \n",
    "                    if chosen_loc[j][0][0]<x4<chosen_loc[j][0][1] and chosen_loc[j][1][0]<y4<chosen_loc[j][1][1]:\n",
    "                        del chosen_loc[j]\n",
    "                        break\n",
    "        \n",
    "        \n",
    "        \n",
    "            if chosen_loc:\n",
    "                for i in loc:\n",
    "                    if i in chosen_loc:\n",
    "                        return x+loc_dict[i][0],y+loc_dict[i][1]\n",
    "            else:\n",
    "                return x+0.1,y+1\n",
    "            \n",
    "        for i in range(len(self.tb)): \n",
    "            x,y= reject_clash(self.tb[i],self.E[i],ban_loc_list)\n",
    "            ban_loc_list.append([x,y])\n",
    "            ban_loc_list.append([x+0.3,y+1.5])\n",
    "            ban_loc_list.append([x+0.3,y])\n",
    "            ban_loc_list.append([x,y+1.5])\n",
    "            plt.text(x,y,numbers[i],fontproperties = font_set_2,zorder=102)\n",
    "            \n",
    "            \n",
    "            \n",
    "        #u1,u2 = [i[0] for i in ban_loc_list]   , [i[1] for i in ban_loc_list]   \n",
    "        #self.ax.plot(u1,u2,\"x\",markersize =4,alpha = 1,c=\"r\",label = \"均值点\" ,zorder=105)    \n",
    "            \n",
    "        for key in keyl.split(\",\"):\n",
    "            x,y = int(key[0]),int(key[1:])\n",
    "\n",
    "            x1 = np.linspace(ticks[x-1],ticks[x],100) \n",
    "\n",
    "            y1 = 5.893*2.4987*x1*yt[y-1]\n",
    "            y2 = 5.893*2.4987*x1*yt[y]\n",
    "\n",
    "            self.ax.plot(x1,y1,alpha = 1,c=\"r\",zorder=100)\n",
    "            self.ax.plot(x1,y2,alpha = 1,c=\"r\",zorder=100)\n",
    "\n",
    "\n",
    "            d1,d2,d3,d4 = 5.893*2.4987*ticks[x-1]*yt[y-1],5.893*2.4987*ticks[x-1]*yt[y],5.893*2.4987*ticks[x]*yt[y-1],5.893*2.4987*ticks[x]*yt[y]\n",
    "\n",
    "            self.ax.vlines(ticks[x-1],min(d1,d2),max(d1,d2),colors=\"r\",zorder=100)\n",
    "\n",
    "            self.ax.vlines(ticks[x],min(d3,d4),max(d3,d4),colors=\"r\",zorder=100)\n",
    "       \n",
    "        plt.savefig(save_path + \".svg\",format = \"svg\",bbox_inches='tight')\n",
    "        svg_to_emf(save_path+ \".svg\")\n",
    "        plt.clf()\n",
    "        plt.close()\n",
    "\n",
    "        \n",
    "# -*- coding: utf-8 -*-\n",
    "\"\"\"\n",
    "1.0.0 格子图remake 自动寻求最优多段拟合方案，速度加快\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "import csv\n",
    "import time\n",
    "import os\n",
    "import gc\n",
    "import pandas as pd\n",
    "import shutil\n",
    "import collections\n",
    "import pandas as pd\n",
    "import csv\n",
    "from PIL import Image\n",
    "import subprocess\n",
    "import numpy as np\n",
    "import matplotlib.pylab as plt\n",
    "from matplotlib.ticker import MultipleLocator\n",
    "from matplotlib.ticker import FormatStrFormatter\n",
    "from sklearn.linear_model import LinearRegression \n",
    "from constant import type_dict_import\n",
    "from matplotlib.font_manager import FontProperties\n",
    "import matplotlib.pylab as plt\n",
    "from settings import poly_path,List,loc,save_path,gis_csv_path,area_csv_path,团簇,垂直水平,inkscape_path,指定类型\n",
    "from matplotlib.font_manager import FontProperties\n",
    "font_set = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=12)\n",
    "font_set2 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=8)\n",
    "font_set_2 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=8,weight =\"bold\")\n",
    "\n",
    "img_save_path = save_path\n",
    "try:\n",
    "    os.mkdir(save_path+ \"\\\\csv\")\n",
    "except:\n",
    "    pass\n",
    "name2 = List.split(\"_\")[-1] + \"_\" + List.split(\"_\")[-2]\n",
    "total = 0\n",
    "\n",
    "rows=[]\n",
    "\n",
    "csv_number=0\n",
    "\n",
    "##########\n",
    "\n",
    "df = pd.read_csv(gis_csv_path,encoding = \"gbk\" ,dtype = {\"num\": object,\"key\":object})\n",
    "type_csv_path = []\n",
    "for root,dirs,files in os.walk(poly_path):        \n",
    "    for file in files:            \n",
    "        if \".csv\" in os.path.join(root,file) and \"信息统计\" not in os.path.join(root,file):\n",
    "            type_csv_path.append(os.path.join(root,file))\n",
    "release_csv_list = []   \n",
    "for i in range(len(df)):\n",
    "    for j in type_csv_path:\n",
    "        if j.endswith(df[\"key\"][i]+\".csv\"):   \n",
    "            shutil.copyfile(j,save_path+\"\\\\csv\"+\"\\\\\"+str(df[\"num\"][i])+\".csv\")\n",
    "            release_csv_list.append([save_path+\"\\\\csv\"+\"\\\\\"+str(df[\"num\"][i])+\".csv\",df[\"key\"][i]])\n",
    "getcolor_dict = {}\n",
    "for i in range(len(df)):\n",
    "    getcolor_dict[df.num[i]] = df.key[i].split(\"_\")[0].split(\".\")[-1]\n",
    "#生成k_dict\n",
    "\n",
    "#########\n",
    "\n",
    "area_csv_list = []\n",
    "for root,dirs,files in os.walk(area_csv_path):        \n",
    "    for file in files:            \n",
    "        area_csv_list.append(os.path.join(root,file))\n",
    "\n",
    "\n",
    "            \n",
    "\n",
    "release_csv_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "013e6822",
   "metadata": {},
   "source": [
    "# 占比csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7c96d168",
   "metadata": {},
   "outputs": [],
   "source": [
    "total = {}\n",
    "for i in release_csv_list:\n",
    "    dic = {}\n",
    "    csv1,key = i\n",
    "    df = pd.read_csv(csv1)\n",
    "    for j in range(len(df)):\n",
    "        x,y = df[\"tb\"][j],df[\"E_sum\"][j]\n",
    "        if y>  4*5.893*1.8099* x: a = 0\n",
    "        elif y>  2*5.893*1.8099* x: a = 1\n",
    "        elif y >  5.893*1.8099* x: a = 2\n",
    "        elif y >  (1.0/3)*5.893*1.8099* x : a = 3    \n",
    "        elif y >= 0: a = 4\n",
    "        elif y >  -(1.0/3)*5.893*1.8099* x : a = 5\n",
    "        elif y >=  -0.5*5.893*1.8099* x: a = 6\n",
    "        elif y >  -(3.0/5)*5.893*1.8099* x : a = 7  \n",
    "        elif y >  -(2.0/3)*5.893*1.8099* x : a = 8  \n",
    "        elif y >=  -5.893*1.8099* x: a = 9\n",
    "        else : a = 10\n",
    "\n",
    "        if x <2: b = 0\n",
    "        elif x<6: b = 1\n",
    "        elif x<10: b = 2\n",
    "        elif x<14: b = 3\n",
    "        elif x<22: b = 4\n",
    "        elif x<30: b = 5\n",
    "        g  = 100*(b+1) + a+1\n",
    "        if g not in dic:\n",
    "            dic[g] = 1\n",
    "        else:\n",
    "            dic[g] += 1\n",
    "    num = sum([dic[g] for g in dic])\n",
    "    c = [[str(a),round(dic[a]/num,5)] for a in dic]\n",
    "    c.sort(key = lambda x : x[1],reverse = True)\n",
    "    if c[0][1] > 0.6321:statu = \"稳态\"\n",
    "    elif c[0][1] > 0.3679:\n",
    "        if c[1][1] > 0.3679:\n",
    "            statu = \"双亚稳态\"\n",
    "        else:\n",
    "            statu = \"单亚稳态\"\n",
    "    else:\n",
    "        statu = \"混沌态\"\n",
    "    total[csv1.split(\"\\\\\")[-1][:-4]] = [statu,num ]+ sum(c,[])\n",
    "    \n",
    "with open((save_path + \"\\\\123.csv\"),'w',newline = \"\") as f_c_csv:\n",
    "    writer = csv.writer(f_c_csv)\n",
    "    writer.writerow([\"群丛编号\",\"群丛状态\",\"总点数\"])\n",
    "    for key in total:\n",
    "        writer.writerow([key] + total[key]) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c267ceff",
   "metadata": {},
   "source": [
    "# 格子图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f1244951",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E:\\oo\\oo\\csv\\1-1.csv\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\python\\lib\\site-packages\\scipy\\optimize\\minpack.py:808: OptimizeWarning: Covariance of the parameters could not be estimated\n",
      "  category=OptimizeWarning)\n",
      "c:\\python\\lib\\site-packages\\numpy\\lib\\function_base.py:393: RuntimeWarning: Mean of empty slice.\n",
      "  avg = a.mean(axis)\n",
      "c:\\python\\lib\\site-packages\\numpy\\core\\_methods.py:154: RuntimeWarning: invalid value encountered in true_divide\n",
      "  ret, rcount, out=ret, casting='unsafe', subok=False)\n",
      "c:\\python\\lib\\site-packages\\numpy\\lib\\function_base.py:2526: RuntimeWarning: Degrees of freedom <= 0 for slice\n",
      "  c = cov(x, y, rowvar)\n",
      "c:\\python\\lib\\site-packages\\numpy\\lib\\function_base.py:2455: RuntimeWarning: divide by zero encountered in true_divide\n",
      "  c *= np.true_divide(1, fact)\n",
      "c:\\python\\lib\\site-packages\\numpy\\lib\\function_base.py:2455: RuntimeWarning: invalid value encountered in multiply\n",
      "  c *= np.true_divide(1, fact)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E:\\oo\\oo\\csv\\2-1.csv\n",
      "2.1 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\2-2.csv\n",
      "2.2 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\2-3.csv\n",
      "2.3 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\3-1.csv\n",
      "3.1 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\3-2.csv\n",
      "3.2 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\3-3.csv\n",
      "3.3 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-1.csv\n",
      "4.1 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-2.csv\n",
      "4.2 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-3.csv\n",
      "4.3 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-4.csv\n",
      "4.4 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-5.csv\n",
      "4.5 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-6.csv\n",
      "4.6 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\4-7.csv\n",
      "4.7 没有找到地域csv\n",
      "E:\\oo\\oo\\csv\\5-1.csv\n",
      "5.1 没有找到地域csv\n"
     ]
    }
   ],
   "source": [
    "dfc = pd.read_csv(gis_csv_path,encoding = \"gbk\" ,dtype = {\"num\": object,\"key\":object})\n",
    "key_num = {}\n",
    "for i in range(len(dfc)):\n",
    "    key_num[dfc.key[i]] = dfc.num[i]\n",
    "for a in release_csv_list:\n",
    "    csv1,key = a\n",
    "    if 指定类型 and csv1.split(\"\\\\\")[-1][:-4] not in 指定类型:\n",
    "        continue\n",
    "    print(csv1)\n",
    "\n",
    "    area = \"地域\" + key.split(\".\")[0] + \".\"\n",
    "    \n",
    "    files = [i for i in area_csv_list if area in i]\n",
    "    if len(files) < 1:\n",
    "        print(key,\"没有找到地域csv\")\n",
    "        continue\n",
    "    elif len(files) > 1:\n",
    "        print(key,\"太多地域csv\")\n",
    "        continue\n",
    "    new_area = csv1.split(\"\\\\\")[-1][:-4]\n",
    "    团簇_sign = False\n",
    "    if new_area in 团簇:\n",
    "        团簇_sign = True\n",
    "    title = \"群丛\" + csv1.split(\"\\\\\")[-1][:-4]\n",
    "    df = pd.read_csv(csv1,engine = \"python\")\n",
    "    if key_num[key] in 垂直水平:\n",
    "        rg,keyword = 垂直水平[key_num[key]][\"分界点\"],垂直水平[key_num[key]][\"拟合方式\"]\n",
    "        k_dict = auto_curve(df,rg,keyword)\n",
    "    else:\n",
    "        k_dict = auto_curve(df,[],None)\n",
    "    max_limit = 30\n",
    "    e = ExecuteCsv_rewrite(files,name2 + \" \" + title,\"\",img_save_path) \n",
    "    e.set_save_path(img_save_path + \"\\\\格子图\")      \n",
    "    e.start_execute(name2 + \" \" + title,csv1,max_limit,k_dict,df.tb,df.E_sum,团簇_sign)\n",
    "    gc.collect() \n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "8966476d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'5.1'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "55147f75",
   "metadata": {},
   "source": [
    "# 群丛分布图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "e97a6e58",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------\n",
      "请确保以下文件都在群系文件夹中\n",
      "如有缺漏会导致中断：\n",
      "1.1.csv\n",
      "2.1.csv\n",
      "2.2.csv\n",
      "2.3.csv\n",
      "3.1.csv\n",
      "3.2.csv\n",
      "3.3.csv\n",
      "4.1.csv\n",
      "4.2.csv\n",
      "4.3.csv\n",
      "4.4.csv\n",
      "4.5.csv\n",
      "4.6.csv\n",
      "4.7.csv\n",
      "5.1.csv\n",
      "--------------------\n",
      "\n",
      "end\n"
     ]
    }
   ],
   "source": [
    "\n",
    "dfc = pd.read_csv(gis_csv_path,encoding = \"gbk\" ,dtype = {\"num\": object,\"key\":object})\n",
    "print(\"--------------------\\n请确保以下文件都在群系文件夹中\\n如有缺漏会导致中断：\")\n",
    "for i in dfc.key:\n",
    "    print(i + \".csv\")\n",
    "print(\"--------------------\\n\")\n",
    "tb_ppe_dict = {}\n",
    "for i in range(len(dfc)):\n",
    "    if dfc.tb_ppe[i] not in tb_ppe_dict:\n",
    "        tb_ppe_dict[dfc.tb_ppe[i]] = [dfc.num[i]]\n",
    "    else:\n",
    "        tb_ppe_dict[dfc.tb_ppe[i]].append(dfc.num[i])\n",
    "\n",
    "\n",
    "for i in tb_ppe_dict:\n",
    "\n",
    "    tb_means = []\n",
    "    E_means = []\n",
    "    \n",
    "    for index,a in enumerate(release_csv_list):\n",
    "        csv1 = a[0]\n",
    "        if csv1.split(\"\\\\\")[-1][:-4] not in tb_ppe_dict[i]:continue\n",
    "        df = pd.read_csv(csv1,engine = \"python\")\n",
    "        tb_means.append(np.mean(df.tb))\n",
    "        E_means.append(np.mean(df.E_sum))\n",
    "    if not tb_means:\n",
    "        print(\"缺少csv:\" )\n",
    "        for c in range(len(dfc)):\n",
    "            if dfc.num[c] in tb_ppe_dict[i]:\n",
    "                print(dfc.key[c],end = \"|\")\n",
    "        print()\n",
    "        continue\n",
    "    e = LatticeImageForAll(tb_means,E_means,name2 + \" 群丛分布\"+str(i),str(i))\n",
    "    e.generate_image(img_save_path + \"\\\\格子图\\\\群丛分布\"+str(i),tb_ppe_dict[i])\n",
    "print(\"end\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dc4834f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
